package model;
import java.io.InputStream;
import java.net.*;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Document;
import org.w3c.dom.NodeList;

import java.util.*;
import commons.*;

/**
 * This showcase the request for flickr panda service using REST style
 * @author zhouy
 *
 */
public class PandaQuery {
	
	
	public PandaQuery(){
		System.setProperty("http.proxyHost", "www-cache.cs.usyd.edu.au");
		System.setProperty("http.proxyPort","8000");
	}
	
	public List<Picture> callPanda(String pandaName){		
		List<Picture> pandaList=new ArrayList<Picture>();
		try{
			String callUrlStr = Constants.REST_ENDPOINT+"?method="+Constants.METHOD+
			"&panda_name="+URLEncoder.encode(pandaName,Constants.ENC)+
			"&per_page="+Constants.DEFAULT_NUMBER+
			"&api_key="+Constants.API_KEY;
			URL callUrl = new URL(callUrlStr);			
			HttpURLConnection urlConnection = (HttpURLConnection)callUrl.openConnection();
			InputStream urlStream = urlConnection.getInputStream();
		
			DocumentBuilder db = DocumentBuilderFactory.newInstance().newDocumentBuilder();
			Document response = db.parse(urlStream);
			
			//print out all titles
			System.out.println("The titles returned are: ");
			NodeList nl = response.getElementsByTagName("photo");
			String idForTags="";
			for (int i = 0; i < nl.getLength(); i ++){
				String name=nl.item(i).
						getAttributes().getNamedItem("title").getTextContent();
				String id=nl.item(i).
						getAttributes().getNamedItem("id").getTextContent();
				pandaList.add(new Picture(name,id));
			}
			urlConnection.disconnect();
		}catch (Exception e){
			System.out.println(e.getMessage());
		}
		return pandaList;
	}
	
	public void callGetInfo(String photo_id){
		try{
			String callUrlStr = Constants.REST_ENDPOINT+"?method="+Constants.METHOD2+
			"&photo_id="+URLEncoder.encode(photo_id,Constants.ENC)+
			"&api_key="+Constants.API_KEY;
			URL callUrl = new URL(callUrlStr);			
			HttpURLConnection urlConnection = (HttpURLConnection)callUrl.openConnection();
			InputStream urlStream = urlConnection.getInputStream();
		
			DocumentBuilder db = DocumentBuilderFactory.newInstance().newDocumentBuilder();
			Document response = db.parse(urlStream);
			
			//print out all titles
			System.out.print("The tags returned are: ");
			NodeList nl = response.getElementsByTagName("tag");
			for (int i = 0; i < nl.getLength(); i ++){
				System.out.print(nl.item(i).
						getAttributes().getNamedItem("raw").getTextContent()+", ");
			}
			System.out.println("");
			System.out.println("");
			System.out.println("");
			urlConnection.disconnect();
		}catch (Exception e){
			System.out.println(e.getMessage());
		}

	}
	
}
